﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;

using Happy.Domain;

namespace Happy.Security.Domain.Users
{
    public static class IUserRepositoryExtentions
    {
        public static void AssertUserNameNotExists(this IUserRepository that, string username)
        {
            if (that.IsUserNameExists(username))
            {
                throw new DomainException(string.Format("用户名 {0} 已经存在"));
            }
        }

        public static bool IsUserNameExists(this IUserRepository that, string username)
        {
            return that.Queryable().Count(UserNameSpecification(username)) > 0;
        }

        public static User FindByUserName(this IUserRepository that, string username)
        {
            return that.Queryable().FirstOrDefault(UserNameSpecification(username));
        }

        private static Expression<Func<User, bool>> UserNameSpecification(string username)
        {
            return (x) => x.UserName == username;
        }
    }
}
